<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use App\Models\Order;
use App\Models\Agent;
use App\Models\Video;
use App\Models\AgentAccountDetail;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use App\Jobs\RecordVisit;

class UpdateOrder implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;


    protected $data;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($data)
    {
        $this->data = $data;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        //订单
        $order = Order::where('no',$this->data['no'])->first();
        if($order->paid_at){
            return;
        }
        //是否扣量
        $is_deduct = 0;
        //代理
        $agent = Agent::find($order->agent_id);
        //扣量比例
        $deduct = $agent->deduct;
        if($deduct>0){
            //已经有多少单没扣量了
            $deduct_counter = $agent->deduct_counter;
            //当前一单计算扣量比例
            // $rate = bcdiv(1, $deduct_counter+1,2)*100;
            //判断是否达到扣量标准
            if($deduct_counter+1>=$deduct){
                $agent->deduct_counter = 0;
                //订单标记要扣量
                $is_deduct = 1;
            }else{
                $agent->deduct_counter = $agent->deduct_counter+1;
            }
        }
        
        cache()->forget("order_video:{$order->video_id}:{$order->openid}");
        DB::beginTransaction();
        try{
            $agent->save();

            $_price = $price = $order->price;
            if($order->type == 'sevenSm'){
                $price = bcmul(0.97,$price,2);
            }
            //更新订单
            $order->update([
                'paid_at' => Carbon::now(),
                'valid' =>1,
                'is_deduct' =>$is_deduct,
                'price'=>$_price,
                'agent_price'=>$price,
                'transaction_id' => $this->data['transaction_id']
            ]);
            
            if($is_deduct==0){
                //手续费
                $charge = bcdiv(bcmul($price,$agent->withdraw_rate??0,4),100,2);
                $income = bcsub($price,$charge,2);
                //增加账户余额
                $account = $agent->agentAccount;
                $account->increment('balance', $income);
                $account->increment('profits', $income);
                //创建日志详情
                AgentAccountDetail::create([
                    'agent_id'=>$agent->id,
                    'number'=>$income,
                    'type'=>1,
                    'video_id'=>$order->video_id,
                ]);
            }
            $video = Video::find($order->video_id);
            $video->increment('paynum', 1);
            //------------ 统计访问 队列 ------------
            $view_params=[
                'code'=>$order->code??'',
                'path'=>'',
                'url'=>'',
                'ip'=>$order->ip,
                'ua'=>$order->ua??'',
                'agent_id'=>$agent->id,
                'openid'=>$order->openid,
                'category'=>5, //1入口，2落地，3播放，4支付，5支付成功
            ];
            RecordVisit::dispatch($view_params);
            //------------ 统计访问 结束 ------------
            DB::commit();
        }catch(Exception $e){
            DB::rollBack();
        }

        
    }
}
